package com.personal.common.utils;

/** 
 * @Description DES算法
 * @author  jun
 * @Copyright 2012 hexing Inc. All rights reserved
 * @time：2012-6-9
 * @version AMI3.0 
 */
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import org.apache.axis.encoding.Base64;

public class DESEncrypt {
	//默认密钥
	private static String defaultKey = "SmartPay";
	//密钥长度
	private static int keyLen = 8;
	//IV向量
	private final static byte[] IV = new byte[]{0x12, 0x34, 0x56, 0x78, (byte) 0x90, (byte) 0xab, (byte) 0xcd, (byte) 0xef};
	//加密对象
	private Cipher encryptCipher = null;
	//解密对象
	private Cipher decryptCipher = null;

	/**
	 * 默认构造
	 * @throws Exception
	 */
	public DESEncrypt() throws Exception {
		this(defaultKey);
	}

	/**
	 * 带密钥参数构造
	 * @param key
	 * @throws Exception
	 */
	public DESEncrypt(String key) throws Exception {
		Security.addProvider(new com.sun.crypto.provider.SunJCE());
		//获取密钥对象
		SecretKey sk = getKey(key);
		//IV向量对象
		IvParameterSpec iv2 = new IvParameterSpec(IV);
		//加密对象
		encryptCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		encryptCipher.init(Cipher.ENCRYPT_MODE, sk, iv2);
		//解密对象
		decryptCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		decryptCipher.init(Cipher.DECRYPT_MODE, sk, iv2);
	}

	public byte[] encrypt(byte[] arrB) throws Exception {
		return encryptCipher.doFinal(arrB);
	}

	/**
	 * 加密方法
	 * @param strIn
	 * @return
	 * @throws Exception
	 */
	public String encrypt(String strIn) throws Exception {
		//将字节数组转成BASE64编码字符串
		return Base64.encode(encrypt(strIn.getBytes()));
	}

	public byte[] decrypt(byte[] arrB) throws Exception {
		return decryptCipher.doFinal(arrB);
	}

	/**
	 * 解密方法
	 * @param strIn
	 * @return
	 * @throws Exception
	 */
	public String decrypt(String strIn) throws Exception {
		//将BASE64编码字符串转成字节数组
		byte[] encryptedByteArray = Base64.decode(strIn);
		return new String(decrypt(encryptedByteArray));
	}
	
	
	
	

	/**
	 * 获取密钥对象，密钥长度为8个字节，不足左边补0
	 * @param key
	 * @return
	 * @throws Exception
	 */
	private SecretKey getKey(String key) throws Exception {
		//密钥长度不足左边补0
		while(key.getBytes("UTF-8").length < keyLen)
			key = "0" + key;
		
		//截取密钥的前8个字节
		byte[] desKey = new byte[8];
		for (int i = 0; i < desKey.length; i++) {
			desKey[i] = key.getBytes("UTF-8")[i];
		}
		
		DESKeySpec ks = new DESKeySpec(desKey);
		SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
		SecretKey sk = skf.generateSecret(ks);
		return sk;
	}
}